//
//  HttpRequest.m
//  RedGrass
//
//  Created by wukong on 2018/12/29.
//  Copyright © 2018年 hongcaosp. All rights reserved.
//

#import "HttpRequest.h"
#import <AFNetworking/AFNetworking.h>
#import "HttpResponse.h"

static ExceptionHandler exceptionHandler;
static NSString  *downLoadTempFilePath = @"user/download";

@interface HttpRequest()

@property (nonatomic) NSString *url;
@property (strong, nonatomic) NSString *token;


@end


@implementation HttpRequest

+(NSString *)host {
    return URL_main;
}
+(void)setExceptionHandler:(ExceptionHandler)eh {
    exceptionHandler = eh;
}

-(instancetype)init {
    self = [super init];
    if (self) {
//        [HttpRequest afnManager].requestSerializer = [AFJSONRequestSerializer serializer];
//        设置请求格式
//        [[HttpRequest afnManager].requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//        [[HttpRequest afnManager].requestSerializer willChangeValueForKey:@"timeoutInterval"];
//        [HttpRequest afnManager].requestSerializer.timeoutInterval = 12.0f;
//        [[HttpRequest afnManager].requestSerializer didChangeValueForKey:@"timeoutInterval"];
        
//        [[HttpRequest afnManager].requestSerializer setValue:SafeStr([BCBTool makeToken]) forHTTPHeaderField:@"token"];
//        [[HttpRequest afnManager].requestSerializer setValue:SafeStr([BCBTool makeUserName]) forHTTPHeaderField:@"username"];
//        [[HttpRequest afnManager].requestSerializer setValue:SafeStr([BCBTool makeLanguageStr]) forHTTPHeaderField:@"lang"];
        //        [[HttpRequest afnManager].requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        //         [[HttpRequest afnManager].requestSerializer setStringEncoding:NSUTF8StringEncoding];
    }
    return self;
}

+(AFHTTPSessionManager *)afnManager {
    static dispatch_once_t onceToken;
    static AFHTTPSessionManager *operationManager;
    dispatch_once(&onceToken, ^{
        operationManager = [AFHTTPSessionManager manager];
        operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
        operationManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/xml",@"text/plain",@"image/jpeg", @"image/png", nil];
        
    });
    return operationManager;
}

+(HttpRequest *)buildRequest:(NSString *)url {
    
    return [self buildRequest:url withHeader:nil];
}

+(HttpRequest *)buildRequest:(NSString *)url withHeader:(NSDictionary *)headers {
    if (headers) {
        for (NSString *key in headers.allKeys) {
            [[HttpRequest afnManager].requestSerializer setValue:[headers valueForKey:key] forHTTPHeaderField:key];
        }
    }
    HttpRequest *request = [HttpRequest new];
    
    request.url = [NSString stringWithFormat:@"%@%@",URL_main,url];
    //NSLog(@"url = %@",request.url);
    return request;
}


-(void)post:(NSDictionary *)params success:(SuccessBlock)sb fail:(FailBlock)fb {
    [self post:params success:sb fail:fb parse:nil];
}

-(void)post:(NSDictionary *)params success:(SuccessBlock)sb fail:(FailBlock)fb parse:(ParseBlock)pb {
    
    NSLog(@"param = %@",params);
    NSLog(@"url== %@",_url);
    
    [[HttpRequest afnManager] POST:_url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        HttpResponse *response = [[HttpResponse alloc] initWith:responseObject];
        if ([response isBusinessOk]) {
            id data = [response getResult];
            if (pb) {
                data = pb(data);
            }
            if (sb) {
                sb(data);
            }
        } else{
            if (exceptionHandler) {
                exceptionHandler([response getBuinessCode],[response getBusinessMsg]);
            }
            if([response getBuinessCode] == -2){
                 RGUserInfoModel *user = [RGUserInfoModel getUserInfo];
                user.token = @"";
                [RGUserInfoModel storeUserInfo:user];
                 KPostNotification(KNotificationLoginStateChange, @NO);
            }else{
                
            }
            if (fb) {
                if([response getBuinessCode] == -2){
                    fb([response getBuinessCode],@"");
                }else{
                    fb([response getBuinessCode],[response getBusinessMsg]);
                }
               
            }
           
            
            //            if([response getBuinessCode] == 10003){//token失效
//                [[BCBReloginAlertViewManager shareInstance] showAlertViewWithErrorCode:[response getBuinessCode]];
//            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSString *errorMsg ;
        switch (error.code) {
            case -1005:
            case -1006:
            case -1007:
            case -1008:
            case -1009:
            {
                errorMsg = @"网络连接失败";
                if (exceptionHandler) {
                    exceptionHandler(error.code,errorMsg);
                }
                if(fb) {
                    fb(error.code,errorMsg);
                }
            }
                break;
                //                    [[XLMReLoginAlertViewManager shareInstance] showAlertViewWithErrorCode:401];
                
            default:
            {
                errorMsg = @"网络错误";
                if (exceptionHandler) {
                    exceptionHandler(error.code,errorMsg);
                }
                if(fb) {
                    fb(error.code,errorMsg);
                }
            }
                break;
        }
    }];
}

-(void) get:(NSDictionary *)params success:(SuccessBlock)sb fail:(FailBlock)fb{
    
    [self get:params success:sb fail:fb parse:nil];
}

-(void) get:(NSDictionary *)params success:(SuccessBlock)sb fail:(FailBlock)fb parse:(ParseBlock)pb{
    [[HttpRequest afnManager] GET:_url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        HttpResponse *response = [[HttpResponse alloc] initWith:responseObject];
        if ([response isBusinessOk]) {
            id data = [response getResult];
            if (pb) {
                data = pb(data);
            }
            if (sb) {
                sb(data);
            }
        } else{
            if (exceptionHandler) {
                exceptionHandler([response getBuinessCode],[response getBusinessMsg]);
            }
            if (fb) {
                fb([response getBuinessCode],[response getBusinessMsg]);
            }
//            if([response getBuinessCode] == -6){//token失效
//                [[BCBReloginAlertViewManager shareInstance] showAlertViewWithErrorCode:[response getBuinessCode]];
//            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSString *errorMsg ;
        switch (error.code) {
            case -1005:
            case -1006:
            case -1007:
            case -1008:
            case -1009:
                errorMsg = @"网络连接失败";
                break;
            default:
                errorMsg = @"网络错误";
                break;
        }
        if (exceptionHandler) {
            exceptionHandler(error.code,errorMsg);
        }
        if(fb) {
            fb(error.code,errorMsg);
        }
    }];
}

//上传图片
-(void) uploadImageWithData:(NSData *)data imgName:(NSString *)imageName params:(NSDictionary *)params success:(SuccessBlock)sb fail:(FailBlock)fb {
    
    NSLog(@"url== %@",_url);
    [[HttpRequest afnManager] POST:_url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //二进制文件，接口key值，文件路径，图片格式
        [formData appendPartWithFileData:data name:@"file" fileName:imageName mimeType:@"image/jpg/png/jpeg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        HttpResponse *response = [[HttpResponse alloc] initWith:responseObject];
        if ([response isBusinessOk]) {
            id data = [response getResult];
            if (sb) {
                sb(data);
            }
        } else{
            if (exceptionHandler) {
                exceptionHandler([response getBuinessCode],[response getBusinessMsg]);
            }
            
            if([response getBuinessCode] == -2){
                RGUserInfoModel *user = [RGUserInfoModel getUserInfo];
                user.token = @"";
                [RGUserInfoModel storeUserInfo:user];
                KPostNotification(KNotificationLoginStateChange, @NO);
            }else{
                
            }
            if (fb) {
                if([response getBuinessCode] == -2){
                    fb([response getBuinessCode],@"");
                }else{
                    fb([response getBuinessCode],[response getBusinessMsg]);
                }
                
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSString *errorMsg ;
        switch (error.code) {
            case -1005:
            case -1006:
            case -1007:
            case -1008:
            case -1009:
            case -1011:
            {
                
                //                NSData *data = [[error userInfo] objectForKey:@"com.alamofire.serialization.response.error.data"];
                //                NSString *str =[[ NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                
                errorMsg = @"网络连接失败";
                if (exceptionHandler) {
                    exceptionHandler(error.code,errorMsg);
                }
                if(fb) {
                    fb(error.code,errorMsg);
                }
            }
                break;
                
                
            default:
            {
                errorMsg = @"网络错误";
                if (exceptionHandler) {
                    exceptionHandler(error.code,errorMsg);
                }
                if(fb) {
                    fb(error.code,errorMsg);
                }
            }
                break;
        }
    }];
}

#pragma mark - 下载
-(void)downloadWithUrl:(NSString *)url progressBlock:(ProgressBlock)progressBlock successBlock:(SuccessBlock)successBlock failBlock:(FailBlock)failBlock {
    NSString *type = nil;
    NSArray *subStringArr = nil;
    
    if (url) {
        subStringArr = [url componentsSeparatedByString:@"."];
        if (subStringArr.count > 0) {
            type = subStringArr[subStringArr.count - 1];
        }
    }
  
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    //响应内容序列化为二进制
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
          NSDictionary *dic = @{
                                @"download":@(downloadProgress.completedUnitCount),
                                @"total":@(downloadProgress.totalUnitCount)
                                };
          if (progressBlock) {
              progressBlock(dic);
          }
      } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
          if (successBlock) {
              //写文件
              dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                  NSData *dataObj = (NSData *)responseObject;
                  //获取Documents文件夹目录,第一个参数是说明获取Doucments文件夹目录，第二个参数说明是在当前应用沙盒中获取，所有应用沙盒目录组成一个数组结构的数据存放
                  NSArray *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
                  NSString *documentsPath = [docPath objectAtIndex:0];
                  NSString *folderPath = [NSString stringWithFormat:@"%@/%@",documentsPath,downLoadTempFilePath];
                  if (![[NSFileManager defaultManager] fileExistsAtPath:folderPath]) {
                      [[NSFileManager defaultManager] createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
                  }
                  NSString *allPath = [NSString stringWithFormat:@"%@/%@/%ld.mp4",documentsPath,downLoadTempFilePath,(long)[[NSDate date] timeIntervalSince1970]];
                  [dataObj writeToFile:allPath atomically:YES];
                  dispatch_async(dispatch_get_main_queue(), ^{
                      successBlock(allPath);
                  });
              });
          }
      } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
          if (failBlock) {
              failBlock(error.code, error.description);
          }
      }];
    
}

#pragma mark - getter

@end
